﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading;

namespace Error
{
    public static class ErrorManagement
    {
        private static object _ob = new object();

        public static void CreateLogFile()
        {
            StreamWriter sw = new StreamWriter("Log.txt");
            DateTime dt = DateTime.Now;
            sw.WriteLine("*****************************************");
            sw.WriteLine("***************Web crawler***************");
            sw.WriteLine("*****************************************");
            sw.WriteLine("Log file created on " + dt.ToLocalTime() + ".");
            sw.WriteLine();
            sw.Close();
        }

        public static void AppendException(Exception exc)
        {            
            Monitor.Enter(_ob);
            StreamWriter sw = new StreamWriter("Log.txt", true);
            DateTime dt = DateTime.Now;
            sw.WriteLine(dt.Month + "/" + dt.Day + "/" + dt.Year + " " + dt.Hour + ":" + dt.Minute + ":" + dt.Second + ":" + dt.Millisecond + " -> " + exc.Message);
            sw.Close();
            Monitor.Exit(_ob);
        }

        public static void ManageException(Exception exc)
        {
            if (!File.Exists("Log.txt"))
            {
                CreateLogFile();               
            }
            AppendException(exc);
        }
    }
}
